

import functools

from utils.handler_util import HandlerUtil
from utils.token_util import Token
from config import APP, SUBJECT


# 管理端
def authenticated(func):
    @functools.wraps(func)
    def wrapper(self, *args, **kwargs):

        head = self.request.headers
        authorization = head.get("Authorization", None)
        if not authorization:
            return self.write(HandlerUtil.set_failure_response(data={}, message="登陆失效，请重新登陆", status=102))
        decode_info = Token.decode_jwt(authorization)
        if not decode_info:
            return self.write(HandlerUtil.set_failure_response(data={}, message="登陆失效，请重新登陆", status=102))
        app, subject, username = decode_info.get("app"), decode_info.get("sub"), decode_info.get("username")
        if str(app) != APP or str(subject) != SUBJECT:
            return self.write(HandlerUtil.set_failure_response(data={}, message="登录了错误的服务", status=103))
        project_list = decode_info.get("project_list", [])
        if str(app) not in project_list:
            return self.write(HandlerUtil.set_failure_response(data={}, message="您没有权限访问该服务", status=103))

        return func(self, *args, **kwargs)

    return wrapper


